import React from 'react';
import MenuConfig from './../../../menuConfig/index';
import { Menu, Icon} from 'antd';
import {NavLink} from 'react-router-dom'
import {connect} from 'react-redux'
import {switchMenu} from './../../redux/action'
import './index.scss'
const { SubMenu } = Menu;

class NavLeft extends React.Component {
    state = {
        currentKey: ''
    }

    componentWillMount() {
        this.mounted = true
        const {dispatch} = this.props;
        let title = window.sessionStorage.getItem('title')
        dispatch(switchMenu(title))
        const menuTreeNode = this.renderMenu(MenuConfig)
        // let currentKey = window.location.hash.replace(/#|\?.*$/g, '')
        let currentKey = `/${window.location.hash.split('/')[1]}/${window.location.hash.split('/')[2]}`
        if(this.mounted) {
            this.setState({
                menuTreeNode,
                currentKey
            })
        }
    }

    //点击左侧菜单
    handleClick({item, key}) {
        const {dispatch} = this.props;
        window.sessionStorage.setItem('title', item.props.title)
        dispatch(switchMenu(item.props.title))
        if(this.mounted) {
            this.setState({
                currentKey: key
            })
        }
    }

    //菜单渲染
    renderMenu = (data) => {
        return data.map((item) => {
            if(item.children) {
                return (
                    <SubMenu key={item.key} title={<span><Icon type={item.icon} /><span>{item.title}</span></span>}>
                        {this.renderMenu(item.children)}
                    </SubMenu>
                )
            }
            return (
                <Menu.Item title={item.title} key={item.key}>
                    {item.icon ? <Icon type={item.icon} /> : ''}<NavLink to={item.key} replace>{item.title}</NavLink> 
                </Menu.Item>
            )
        })
    }

    componentWillUnmount() {
        this.mounted = false;
    }

    render() {
        return (
            <div>
                <div className="logo">
                    <img src="/assets/logo-ant.svg" alt="" />
                    <h1>Gas</h1>
                </div>
                <Menu style={{ width: 185 }} theme="dark" mode="inline" defaultOpenKeys={[this.state.currentKey]} selectedKeys={[this.state.currentKey]} onClick={(type) => {this.handleClick(type)}}>
                    {this.state.menuTreeNode}
                </Menu>
            </div>
        );
    }
}

export default connect()(NavLeft);